<template>
  <div>
    <h1>聊天室</h1>
    <ul>
      <li v-for="(msg, index) in list" :key="index">{{ msg }}</li>
    </ul>
    <input type="text" v-model.trim="message" />
    <button @click="sendMessage">发送消息</button>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      message: "",
      list: [],
    };
  },
  mounted() {
    // 文档：https://www.yuque.com/xpromise/fontend/sy7xax007n3s7pdg
    // 1. 链接上webSocket服务器
    this.ws = new WebSocket("ws://192.168.14.81:5000");
    // 3. 接受消息
    this.ws.onmessage = (e) => {
      this.list.push(e.data);
    };
  },
  methods: {
    sendMessage() {
      if (!this.message) return;
      // 2. 点击按钮，向服务器发送消息
      this.ws.send(this.message);

      this.list.push(this.message);

      this.message = "";
    },
  },
};
</script>

<style></style>
